﻿using System;
using System.Collections.Generic;
using chatGUI.DataBase.Entity;
using chatGUI.DataBase.Helper;
using chatGUI.Model;


namespace chatGUI.DataBase.Dao;

public sealed class FriendDao{
    private static readonly IFreeSql  fsql= SqlHelper.FSql;

    public static FriendList SelectById(string uid,string fid){
        return fsql.Select<FriendList>().Where(f => f.Uid == uid && f.Fid == fid).ToOne();
    }
    
    /// <summary>
    /// 查询一个用户的所有好友
    /// </summary>
    /// <param name="uid">用户id</param>
    /// <returns></returns>
    public static List<FriendList> SelectAllFriends(string uid){
        return fsql.Select<FriendList>().Where(f=>f.Uid == uid).ToList();
    }

    /// <summary>
    /// 通过模糊匹配一个用户的好友名称
    /// </summary>
    /// <param name="uid">用户id</param>
    /// <param name="key">名称关键字</param>
    /// <returns></returns>
    public static List<FriendList> SelectLikeNickName(string uid,string key){
        return fsql.Select<FriendList>().Where(f =>f.Uid == uid && f.NickName.Contains(key)).ToList();
    }

    public static int Insert(FriendList friend){
        try {
            return fsql.Insert(friend).ExecuteAffrows();
        }
        catch (Exception) {
            return 0;
        }
    }

    /// <summary>
    /// 请先清空再使用, 无法重复插入
    /// </summary>
    /// <param name="friends">好友列表</param>
    /// <param name="uid">当前登录的用户id</param>
    /// <returns></returns>
    public static int InsertList(string uid,List<friendListModel> friends){
        
        List<FriendList> friendLists = new List<FriendList>();
        foreach (var friend in friends) {
            friendLists.Add(new FriendList{
                Uid = uid,Fid = friend.Id,AvatarUrl = friend.AvatarUrl,
                NickName = friend.FriendNickName
            });
        }
        try {
            return fsql.Insert(friendLists).ExecuteAffrows();
        }
        catch (Exception) {
            return 0;
        }
    }


    public static int InsertList(List<FriendList> friends){
        try {
            return fsql.Insert(friends).ExecuteAffrows();
        }
        catch (Exception) {
            return 0;
        }
    }



    public static int Update(FriendList friend){
        try {
            fsql.GetRepository<FriendList>().Update(friend);
            return 1;
        }
        catch (Exception) {
            return 0;
        }
    }

    public static int DeleteById(string uid,string fid){
        try {
            return fsql.Delete<FriendList>().Where(f => f.Fid == fid && f.Uid ==uid).ExecuteAffrows();
        }
        catch (Exception) {
            return 0;
        }
    }


    public static int DeleteAll(){
        try {
            return fsql.Select<FriendList>().ToDelete().ExecuteAffrows();
        }
        catch (Exception) {
            return 0;
        }
    }
}